<script setup lang="ts">
import { useCountdown } from '@/common/composables/useCountDown';
import type { SignInSMSDTO } from '@/index';
import { useUserStore } from '@/stores';
import { message, type FormInstance, type FormProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useRequest } from 'vue-request';

defineOptions({
  name: "SignInFormPhone"
})

interface FormState {
  phoneNumber: number | undefined,
  code: number | undefined,
}
const formState = reactive<SignInSMSDTO>({
  phoneNumber: undefined,
  code: undefined
})


const userStore = useUserStore()
const formRef = ref<FormInstance>()


const formProps: FormProps = {
  labelCol: {
    span: 6,
  },
  labelAlign: 'left',
  wrapperCol: {
    span: 18
  },
}

const rules: Record<keyof FormState, Rule[]> = {
  phoneNumber: [
    {
      required: true,
      message: "请输入您的手机号码",
    },
    {
      len: 11,
      message: "手机号码长度需11位"
    }
  ],
  code: [
    {
      required: true,
      message: "请输入验证码"
    },
    {
      len: 6,
      message: "验证码格式不正确"
    }
  ]
}

const testAccount = reactive({
  phoneNumber: "18500000000",
  nickname: '小Q是最厉害的程序员',
  avatarUrl: '/default-avatar.jpg'
})

const { loading: sendCodeLoading, run: sendCode } = useRequest(sendSMSService, {
  onError: () => message.error("发送验证码错误,请稍后重试！"),
  onSuccess: ({ data }) => {
    if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
    startCountdown()
    message.success("发送验证码成功")
  }
})

const { loading: signInLoading, run: signIn } = useRequest(signInSMSService, {
  onSuccess: ({ data }) => {
    if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
    console.log("data:", data);

    if (data.data) {
      userStore.setToken(data.data)
      message.success('登录成功')
    }
  },
  onError: (err) => {
    console.log(err);
    message.error("登录失败,发生错误")
  }
})

const { remainingTime, start: startCountdown, isRunning: isStartCountdown } = useCountdown()


/**重置表单 */
const handleResetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

/**发送验证码 */
const handleSendSMS = async () => {
  if (!formRef.value) return
  formRef.value.validate(['phoneNumber']).then(({ phoneNumber }) => sendCode(phoneNumber))
}

/**表单提交 */
const handleSubmit = async () => {

  if (!formRef.value) return
  // 校验表单信息并登录
  formRef.value.validate().then(({ phoneNumber, code }) => {
    console.log("phoneNumber:", phoneNumber);

    if (phoneNumber == testAccount.phoneNumber) {
      userStore.setUserInfo({ ...testAccount })
      userStore.setToken("testToken")
      message.success("登录成功")
      return handleResetForm()
    } else {
      signIn({
        phoneNumber,
        code: Number(code)
      })
      handleResetForm()
    }

  })
}


const isLoading = computed(() => sendCodeLoading.value || signInLoading.value)


defineExpose({
  submit: handleSubmit
})



</script>

<template>
  <div class="form-content">
    <a-spin tip="加载中" :spinning="isLoading">
      <a-form :rules="rules" class="form-content-form" v-bind="{ ...formProps }" ref="formRef" :model="formState">
        <p class="placeholder ">测试账号:18500000000,验证码满足条件即可</p>
        <a-form-item label="手机号码" name="phoneNumber">
          <a-input v-model:value="formState.phoneNumber" placeholder="请输入您的手机号码" :maxlength="11" />
        </a-form-item>
        <a-form-item label="验证码" name="code">
          <a-space size="middle">
            <a-input v-model:value="formState.code" placeholder="请输入验证码" :maxlength="6" />
            <a-button type="primary" @click="handleSendSMS" :disabled="isStartCountdown">{{ isStartCountdown ?
              `${remainingTime}秒` : "发送"
              }}</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<style scoped lang="scss">
.form {
  &-title {
    font-size: var(--text-lg);
  }

  &-content {
    display: flex;
    justify-content: center;
    flex: 1;
    padding: var(--gap-lg);
    margin-top: var(--gap-lg);
  }

  &-button {
    &--login {
      width: 100%;
    }
  }

  &-operate {
    margin-top: var(--gap-lg);
  }
}
</style>